import express from "express";
import https from "https";
import fs from "fs";
import path from "path";

import * as config from "../config";

const privateKey = fs.readFileSync(
  path.join(__dirname, "../", "./ssl/feifan.key"),
  "utf8"
);
const certificate = fs.readFileSync(
  path.join(__dirname, "../", "./ssl/feifan.pem"),
  "utf8"
);
const credentials = {
  key: privateKey,
  cert: certificate,
};
const app = express();
//cookie
import parser from "cookie-parser";
app.use(parser(config.key));
//token验证中间件
import token from "../cookie/token";
app.use(token);
//图片防盗链中间件
import { untheft } from "../theft/theft";
app.use(untheft);

app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

//日志中间件
import log from "../log";
app.use(log);

//文章
import article from "./article";
app.use("/api/article", article);
import articlecomnent from "./articlecomment";
app.use("/api/articlecomment", articlecomnent);
import top from "./top";
app.use("/api/article", top);
//user表
import user from "./user";
app.use("/api/user", user);
//评论中间件
import commemt from "./commemt";
app.use("/api/comment", commemt);

//错误处理中间件
import errhandle from "./middleware/errhandle";
app.use(errhandle);

if (config.isHttps) {
  const httpsServer = https.createServer(credentials, app);
  httpsServer.listen(443, () => {
    console.log(`HTTPS Server is running on: https://localhost:${443}`);
  });
} else {
  app.listen(config.httpPort, () => {
    console.log(`端口${config.httpPort}已开启服务`);
  });
}
